// let that;



class Table{

    constructor(data){
        // that = this;
        this.data = data;
        this.tbody = document.querySelector('.my_table tbody');
        this.searchPrice = document.querySelector('.search_1');
        this.searchProduct = document.querySelector('.search_2');
        this.init();
    }

    // 初始化
    init(){
        this.searchPrice.onclick = this.searchPriceFn.bind(this);
        this.searchProduct.onclick = this.searchProductFn.bind(this);
        this.updateNode(this.data);
    }

    // 更新table
    updateNode(data){
        this.tbody.innerHTML = '';
        data.forEach(value => {
            let tr = document.createElement('tr');
            let tds = `<td>${value.id}</td><td>${value.pname}</td><td>${value.price}</td>`;
            tr.innerHTML = tds;
            this.tbody.appendChild(tr);
        });
    }

    // 按价格查询
    searchPriceFn(){
        let newArr;
        let startPrice = document.querySelector('.start').value.trim();
        let endPrice = document.querySelector('.end').value.trim();
        if(isNaN(Number(startPrice)) || isNaN(Number(endPrice))) {
            this.tbody.innerHTML = '';
            return;
        }
        if(!startPrice && !endPrice){
            newArr = this.data;
        } else{
            newArr = this.filterProduct(startPrice, endPrice);
        }
        this.updateNode(newArr);
    }
    // 按价格过滤商品
    filterProduct(startPrice, endPrice){
        if(startPrice && !endPrice){
            return this.data.filter(value => value.price >= startPrice);
        }
        if(!startPrice && endPrice){
            return this.data.filter(value => value.price < endPrice);
        }
        return this.data.filter(value => value.price >= startPrice && value.price <= endPrice);
    }
    // 按商品名称查询
    searchProductFn(){
        let productName = document.querySelector('.name1').value.trim();
        let newArr = []
        if(!productName){
            this.init();
            return
        }
        this.data.some(value => {
            value.pname == productName && newArr.push(value);
            return true;
        });
        this.updateNode(newArr);
    }
}

const data = [
    {id: 1, pname: '小米', price: 3999},
    {id: 2, pname: 'oppo', price: 999},
    {id: 3, pname: '荣耀', price: 1299},
    {id: 4, pname: '华为', price: 1999}
]

let table = new Table(data);